require File.dirname(File.expand_path(__FILE__))+'/mailer'
require 'pstore'

module Opticon
  module Notifier
    # Send failure notifications via email to the given list of recipients.
    # 
    # To set options, configure Opticon::Mailer the same way you
    # would any other ActionMailer. For example, to send via SMTP:
    # 
    #   Opticon::Mailer.delivery_method = :smtp
    #   
    #   Opticon::Mailer.server_settings = {
    #     :address => "mail.nowhere.foo",
    #     :domain => "nowhere.foo",
    #     :authentication => :login,
    #     :user_name => "mail_user",
    #     :password => "topsecret"
    #   }
    # 
    class Email
      attr_accessor :recipients, :from
      
      # The same notification will not be resent over and over again unless
      # this is set to true.
      @@resend = false
      
      def initialize(recipients, options = {:from => "opticon@#{ENV['HOSTNAME']}"})
        @recipients = recipients
        @from = options[:from]
      end
      
      def notify(failures)
        failures = [failures] unless failures.kind_of? Array
        
        failures_by_uri = {}
        failures.each do |f|
          failures_by_uri[f.uri] ||= []
          failures_by_uri[f.uri] << f
        end
        
        if ARGV.include?("-v")
          puts "Notifying #{recipients.inspect} about #{failures.size} failures:"
          failures.each{|f| puts "  #{f.failure_message}"}
        end
        
        failures_by_uri.each do |uri, failures|
          Opticon::Mailer.deliver_failure_notification(
            uri,
            failures.collect{|f| f.failure_message}.join("\n"),
            recipients, from
          )
        end
      end
    end
    
    # Dummy notifier used in testing. It doesn't do anything other than store
    # the error_messages given to notify in the object's notifications attribute.
    class Dummy
      attr_accessor :notifications
    
      def initialize()
        @notifications = []
      end
    
      def notify(failures)
        @notifications << failures
      end
    end
  end
end